#!/bin/bash

# SSL证书自动获取和配置脚本 - 东宁百事通
# 使用Let's Encrypt为 home.dongning.fun 获取免费SSL证书

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置变量
DOMAIN="home.dongning.fun"
EMAIL="admin@dongning.fun"  # 请修改为您的邮箱
WEBROOT="/var/www/certbot"

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "请使用root用户运行此脚本"
        exit 1
    fi
}

# 检查域名DNS解析
check_dns() {
    log_info "检查域名DNS解析..."
    
    local server_ip=$(curl -s ifconfig.me)
    local domain_ip=$(dig +short $DOMAIN)
    
    if [[ "$domain_ip" == "$server_ip" ]]; then
        log_success "域名DNS解析正确: $DOMAIN -> $server_ip"
    else
        log_warning "域名DNS解析可能有问题:"
        log_warning "服务器IP: $server_ip"
        log_warning "域名解析IP: $domain_ip"
        read -p "是否继续？(y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 安装Certbot
install_certbot() {
    log_info "安装Certbot..."
    
    # 检测操作系统
    if command -v apt-get &> /dev/null; then
        apt-get update
        apt-get install -y certbot python3-certbot-nginx
    elif command -v yum &> /dev/null; then
        yum install -y epel-release
        yum install -y certbot python3-certbot-nginx
    else
        log_error "不支持的操作系统"
        exit 1
    fi
    
    log_success "Certbot安装完成"
}

# 创建webroot目录
setup_webroot() {
    log_info "设置webroot目录..."
    
    mkdir -p $WEBROOT
    chown -R www-data:www-data $WEBROOT 2>/dev/null || chown -R nginx:nginx $WEBROOT 2>/dev/null || true
    
    log_success "Webroot目录设置完成: $WEBROOT"
}

# 配置临时Nginx
setup_temp_nginx() {
    log_info "配置临时Nginx配置..."
    
    cat > /etc/nginx/sites-available/temp-ssl << EOF
server {
    listen 80;
    server_name $DOMAIN;
    
    location /.well-known/acme-challenge/ {
        root $WEBROOT;
    }
    
    location / {
        return 200 'SSL setup in progress...';
        add_header Content-Type text/plain;
    }
}
EOF

    # 启用临时配置
    ln -sf /etc/nginx/sites-available/temp-ssl /etc/nginx/sites-enabled/temp-ssl
    
    # 禁用默认配置（如果存在）
    rm -f /etc/nginx/sites-enabled/default
    rm -f /etc/nginx/sites-enabled/dongning.conf
    
    # 测试并重载Nginx
    nginx -t
    systemctl reload nginx
    
    log_success "临时Nginx配置完成"
}

# 获取SSL证书
obtain_certificate() {
    log_info "获取SSL证书..."
    
    certbot certonly \
        --webroot \
        --webroot-path=$WEBROOT \
        --email $EMAIL \
        --agree-tos \
        --no-eff-email \
        --domains $DOMAIN \
        --non-interactive
    
    if [[ $? -eq 0 ]]; then
        log_success "SSL证书获取成功"
    else
        log_error "SSL证书获取失败"
        exit 1
    fi
}

# 配置生产Nginx
setup_production_nginx() {
    log_info "配置生产环境Nginx..."
    
    # 删除临时配置
    rm -f /etc/nginx/sites-enabled/temp-ssl
    
    # 启用生产配置
    ln -sf /var/www/dongning/nginx/conf.d/dongning.conf /etc/nginx/sites-enabled/dongning.conf
    
    # 测试配置
    nginx -t
    
    if [[ $? -eq 0 ]]; then
        systemctl reload nginx
        log_success "生产环境Nginx配置完成"
    else
        log_error "Nginx配置测试失败"
        exit 1
    fi
}

# 设置证书自动续期
setup_auto_renewal() {
    log_info "设置证书自动续期..."
    
    # 创建续期脚本
    cat > /usr/local/bin/certbot-renew.sh << 'EOF'
#!/bin/bash
certbot renew --quiet --post-hook "systemctl reload nginx"
EOF

    chmod +x /usr/local/bin/certbot-renew.sh
    
    # 添加到crontab
    (crontab -l 2>/dev/null; echo "0 12 * * * /usr/local/bin/certbot-renew.sh") | crontab -
    
    log_success "证书自动续期设置完成"
}

# 测试SSL配置
test_ssl() {
    log_info "测试SSL配置..."
    
    sleep 5
    
    if curl -s -I https://$DOMAIN | grep -q "HTTP/2 200"; then
        log_success "SSL配置测试通过"
        log_success "网站访问地址: https://$DOMAIN"
    else
        log_warning "SSL配置可能有问题，请手动检查"
    fi
}

# 显示证书信息
show_certificate_info() {
    log_info "证书信息:"
    certbot certificates
    
    log_info "证书文件位置:"
    echo "  证书文件: /etc/letsencrypt/live/$DOMAIN/fullchain.pem"
    echo "  私钥文件: /etc/letsencrypt/live/$DOMAIN/privkey.pem"
    echo "  CA证书: /etc/letsencrypt/live/$DOMAIN/chain.pem"
}

# 主函数
main() {
    log_info "开始SSL证书配置 - 域名: $DOMAIN"
    
    check_root
    check_dns
    install_certbot
    setup_webroot
    setup_temp_nginx
    obtain_certificate
    setup_production_nginx
    setup_auto_renewal
    test_ssl
    show_certificate_info
    
    log_success "🎉 SSL证书配置完成！"
    log_info "您的网站现在可以通过 https://$DOMAIN 访问"
    log_info "证书将自动续期，无需手动操作"
}

# 执行主函数
main "$@"